package com.ramnight.unify.kit;

import java.util.Arrays;
import java.util.stream.Collectors;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;

@SuppressWarnings("unchecked")
public class UnifyHolder {
	private Object[] objs;

	private String string;

	private UnifyHolder(Object[] objs) {
		this.objs = objs;
	}

	public static UnifyHolder of(Object... objects) {
		return new UnifyHolder(objects);
	}

	public static UnifyHolder empty() {
		return new UnifyHolder(null);
	}

	public Object getObject(int index) {
		if (objs == null) {
			return null;
		}
		return index < objs.length ? objs[index] : null;
	}

	public <T> void set(int index, T obj) {
		if (objs == null) {
			objs = new Object[index + 1];
		}
		if (index < objs.length) {
			objs[index] = obj;
		} else {
			Object[] newObjs = Arrays.copyOf(objs, index + 1 + 1);
			newObjs[index] = obj;
			objs = newObjs;
		}
	}

	public <T> void set(T obj) {
		set(0, obj);
	}

	public boolean isEmpty() {
		return get() == null;
	}

	public <T> T get(int index) {
		Object r = getObject(index);
		return r == null ? null : (T) r;
	}

	public <T> T get() {
		return get(0);
	}

	public <T> T get0() {
		return get(0);
	}

	public <T> T get1() {
		return get(1);
	}

	public <T> T get2() {
		return get(2);
	}

	public <T> T get3() {
		return get(3);
	}

	public <T> T get4() {
		return get(4);
	}

	public <T> T get5() {
		return get(5);
	}

	@Override
	public String toString() {
		if (string != null) {
			return string;
		}
		string = Joiner.on("_").join(Lists.newArrayList(objs).stream().map(String::valueOf).collect(Collectors.toList()));
		return string;
	}

	@Override
	public boolean equals(Object anObject) {
		return this.toString().equals(String.valueOf(anObject));
	}

	@Override
	public int hashCode() {
		return this.toString().hashCode();
	}
}
